/**
 * Copyright (C) 2007 The AsyncMail Group <asyncmail@googlegroups.com>
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *         http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.googlecode.asyncmail.smtpserver.handler;

import org.apache.commons.logging.Log;
import org.springframework.beans.factory.annotation.Required;

import com.googlecode.asyncmail.common.DSNStatus;
import com.googlecode.asyncmail.common.ExtensibleHandler;
import com.googlecode.asyncmail.common.MailEnvelope;
import com.googlecode.asyncmail.common.WiringException;
import com.googlecode.asyncmail.smtp.SMTPRequest;
import com.googlecode.asyncmail.smtp.SMTPResponse;
import com.googlecode.asyncmail.smtp.SMTPResponseImpl;
import com.googlecode.asyncmail.smtp.SMTPRetCode;
import com.googlecode.asyncmail.smtpserver.SMTPSession;
import com.googlecode.asyncmail.smtpserver.core.CommandHandler;

import java.util.Collection;
import java.util.LinkedList;
import java.util.List;

/**
 * handles DATA command
 */
public class DataCmdHandler implements CommandHandler, ExtensibleHandler {

    private Log logger;

    @Required
    public void setLogger(Log logger) {
        this.logger = logger;
    }

    protected Log getLogger() {
        return logger;
    }

    public final class DataConsumerLineHandler implements LineHandler {
        /**
         * @see com.googlecode.asyncmail.smtpserver.LineHandler#onLine(com.googlecode.asyncmail.smtpserver.SMTPSession,
         *      byte[])
         */
        public void onLine(SMTPSession session, byte[] line) {
            // Discard everything until the end of DATA session
            if (line.length == 3 && line[0] == 46) {
                session.popLineHandler();
            }
        }
    }

    private final class DataLineFilterWrapper implements LineHandler {

        private DataLineFilter filter;

        private LineHandler next;

        public DataLineFilterWrapper(DataLineFilter filter, LineHandler next) {
            this.filter = filter;
            this.next = next;
        }

        public void onLine(SMTPSession session, byte[] line) {
            filter.onLine(session, line, next);
        }

    }

    /**
     * Static RFC822DateFormat used to generate date headers
     */
    // TODO reenable
    // private final static RFC822DateFormat rfc822DateFormat = new
    // RFC822DateFormat();
    // Keys used to store/lookup data in the internal state hash map
    private LineHandler lineHandler;

    public synchronized LineHandler getLineHandler() {
        return lineHandler;
    }

    public synchronized void setLineHandler(LineHandler lineHandler) {
        this.lineHandler = lineHandler;
    }

    /**
     * process DATA command
     * 
     * @see com.googlecode.asyncmail.smtpserver.core.CommandHandler#onCommand(SMTPSession)
     */
    public SMTPResponse onCommand(SMTPSession session, SMTPRequest command) {
        SMTPResponse response = doDATAFilter(session, command.getArgument());

        if (response == null) {
            return doDATA(session, command.getArgument());
        } else {
            return response;
        }
    }

    /**
     * Handler method called upon receipt of a DATA command. Reads in message
     * data, creates header, and delivers to mail server service for delivery.
     * 
     * @param session
     *                SMTP session object
     * @param argument
     *                the argument passed in with the command by the SMTP client
     */
    private SMTPResponse doDATA(SMTPSession session, String argument) {
        session.pushLineHandler(getLineHandler());

        return new SMTPResponseImpl(SMTPRetCode.DATA_READY,
                "Ok Send data ending with <CRLF>.<CRLF>");
    }

    /**
     * @see com.googlecode.asyncmail.smtpserver.core.CommandHandler#getImplCommands()
     */
    public Collection<String> getImplCommands() {
        Collection<String> implCommands = new LinkedList<String>();
        implCommands.add("DATA");

        return implCommands;
    }

    /**
     * @see com.googlecode.asyncmail.smtpserver.ExtensibleHandler#getMarkerInterfaces()
     */
    public List<Class<?>> getMarkerInterfaces() {
        List<Class<?>> classes = new LinkedList<Class<?>>();
        classes.add(DataLineFilter.class);
        return classes;
    }

    /**
     * @see com.googlecode.asyncmail.smtpserver.ExtensibleHandler#wireExtensions(java.lang.Class,
     *      java.util.List)
     */
    public void wireExtensions(Class<?> interfaceName, List<?> extension)
            throws WiringException {
        if (DataLineFilter.class.equals(interfaceName)) {
            LineHandler lineHandler = new DataConsumerLineHandler();
            for (int i = extension.size() - 1; i >= 0; i--) {
                lineHandler = new DataLineFilterWrapper(
                        (DataLineFilter) extension.get(i), lineHandler);
            }
            setLineHandler(lineHandler);
        }
    }

    private SMTPResponse doDATAFilter(SMTPSession session, String argument) {
        if ((argument != null) && (argument.length() > 0)) {
            return new SMTPResponseImpl(
                    SMTPRetCode.SYNTAX_ERROR_COMMAND_UNRECOGNIZED, DSNStatus
                            .getStatus(DSNStatus.PERMANENT,
                                    DSNStatus.DELIVERY_INVALID_ARG)
                            + " Unexpected argument provided with DATA command");
        }
        if (!session.getState().containsKey(SMTPSession.MAIL_ENVELOPE)) {
            return new SMTPResponseImpl(SMTPRetCode.BAD_SEQUENCE, DSNStatus
                    .getStatus(DSNStatus.PERMANENT, DSNStatus.DELIVERY_OTHER)
                    + " No sender specified");
        } else if (((MailEnvelope) session.getState().get(
                SMTPSession.MAIL_ENVELOPE)).getRecipients() == null
                || ((MailEnvelope) session.getState().get(
                        SMTPSession.MAIL_ENVELOPE)).getRecipients().size() == 0) {
            return new SMTPResponseImpl(SMTPRetCode.BAD_SEQUENCE, DSNStatus
                    .getStatus(DSNStatus.PERMANENT, DSNStatus.DELIVERY_OTHER)
                    + " No recipients specified");
        }
        return null;
    }

}
